package controller

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntityManager"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Slice"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/httpserver"
	"go-fox-edge-kernel-manager/utils/PageUtils"
	"strconv"
	"strings"
)

type operateMonitorTaskManageController struct {
}

func (e *operateMonitorTaskManageController) init() {
	httpserver.Server.POST("/device/operate/task/monitor/entities", e.selectEntityList)
	httpserver.Server.POST("/device/operate/task/monitor/page", e.selectPageList)
	httpserver.Server.GET("/device/operate/task/monitor/entity", e.queryEntity)
	httpserver.Server.POST("/device/operate/task/monitor/entity", e.insertEntity)
	httpserver.Server.PUT("/device/operate/task/monitor/entity", e.updateEntity)
	httpserver.Server.DELETE("/device/operate/task/monitor/entity", e.deleteEntity)
	httpserver.Server.DELETE("/device/operate/task/monitor/entities", e.deleteEntityList)
}

func (e *operateMonitorTaskManageController) selectEntityList(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	return e.selectList(context, body, false)
}

func (e *operateMonitorTaskManageController) selectPageList(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	return e.selectList(context, body, true)
}

func (e *operateMonitorTaskManageController) selectList(context httpserver.Context, body map[string]interface{}, isPage bool) (interface{}, error) {
	entityList := commEntityManager.FindEntityList(edgeEntity.Type.OperateMonitorTaskEntity.Type(), func(value commEntity.IEntity) bool {
		entity := value.(*edgeEntity.OperateMonitorTaskEntity)

		result := true

		if Map.Has(body, "templateName") {
			result = result && entity.TemplateName == body["templateName"]
		}
		if Map.Has(body, "deviceType") {
			result = result && entity.DeviceType == body["deviceType"]
		}
		if Map.Has(body, "manufacturer") {
			result = result && entity.Manufacturer == body["manufacturer"]
		}

		return result
	})

	// 获得分页数据
	if isPage {
		result := PageUtils.GetPageList(entityList, body)
		list := result["list"]
		e.addDeviceCount(list.([]map[string]interface{}))
		return result, nil
	} else {
		result := commEntity.BuildMapList(entityList)
		e.addDeviceCount(result)
		return result, nil
	}
}

func (e *operateMonitorTaskManageController) addDeviceCount(list []map[string]interface{}) {
	type2count := make(map[string]int)
	for _, data := range list {
		key := Map.GetString(data, "manufacturer", "") + ":" + Map.GetString(data, "deviceType", "")
		type2count[key] = 0
	}

	// 计算每个设备类型的设备数量
	commEntityManager.FindEntityList(edgeEntity.Type.DeviceEntity.Type(), func(value commEntity.IEntity) bool {
		entity := value.(*edgeEntity.DeviceEntity)

		key := entity.Manufacturer + ":" + entity.DeviceType
		val, ok := type2count[key]
		if !ok {
			return false
		}
		type2count[key] = val + 1
		return false
	})

	for _, data := range list {
		key := Map.GetString(data, "manufacturer", "") + ":" + Map.GetString(data, "deviceType", "")

		countDeviceType, ok := type2count[key]
		if !ok {
			countDeviceType = 0
		}

		deviceIds := Map.GetSlice(data, "deviceIds", nil)

		data["countDeviceType"] = countDeviceType
		data["countDeviceBind"] = len(deviceIds)
	}

	return
}

func (e *operateMonitorTaskManageController) queryEntity(context httpserver.Context) (interface{}, error) {
	str := context.Query("id")
	if str == "" {
		return nil, errors.New("输入的id为null")
	}

	id, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		return nil, err
	}

	exist := commEntityManager.GetEntityById(edgeEntity.Type.OperateMonitorTaskEntity.Type(), id)
	if exist == nil {
		return nil, errors.New("实体不存在")
	}

	return commEntity.BuildMap(exist), nil
}

func (e *operateMonitorTaskManageController) insertEntity(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	delete(body, "id")
	return e.insertOrUpdate(context, body)
}

func (e *operateMonitorTaskManageController) updateEntity(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	return e.insertOrUpdate(context, body)
}

func (e *operateMonitorTaskManageController) insertOrUpdate(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	// 提取业务参数
	templateName := Map.GetString(body, "templateName", "")
	deviceType := Map.GetString(body, "deviceType", "")
	manufacturer := Map.GetString(body, "manufacturer", "")
	templateParam := Map.GetSlice(body, "templateParam", nil)
	taskParam := Map.GetMap(body, "taskParam", nil)
	deviceIds := Map.GetSlice(body, "deviceIds", nil)

	// 简单校验参数
	if Method.HasNull(templateName, manufacturer, deviceType, deviceIds, templateParam, taskParam) {
		return nil, errors.New("参数不能为空: templateName, manufacturer, deviceType, deviceIds, templateParam, taskParam")
	}

	// 构造作为参数的实体
	entity := edgeEntity.Type.OperateMonitorTaskEntity.Instance()
	entity.TemplateName = templateName
	entity.DeviceType = deviceType
	entity.Manufacturer = manufacturer
	entity.TaskParam = taskParam
	entity.TemplateParam = Slice.ToMapList(templateParam)
	entity.DeviceIds = Slice.ToInt64List(deviceIds)
	Map.SetDefaultValue(entity.TaskParam, "timeMode", "interval")
	Map.SetDefaultValue(entity.TaskParam, "timeUnit", "second")
	Map.SetDefaultValue(entity.TaskParam, "timeInterval", int64(1))

	// 新增/修改实体：参数不包含id为新增，包含为修改
	if !Map.Has(body, "id") {
		exist, err := commEntityManager.GetEntityByServiceKey(entity.Type(), entity.MakeServiceKey())
		if err != nil {
			return nil, err
		}
		if exist != nil {
			return nil, errors.New("实体已存在")
		}

		err = commEntityManager.InsertEntity(entity)
		if err != nil {
			return nil, err
		}

		return nil, nil
	} else {
		id := Map.GetInt64(body, "id", 0)

		exist := commEntityManager.GetEntityById(entity.Type(), id)
		if exist == nil {
			return nil, errors.New("实体不存在")
		}

		// 修改数据
		entity.BaseEntity.Id = id
		entity.GetBaseEntity().CreateTime = exist.GetBaseEntity().CreateTime
		entity.GetBaseEntity().UpdateTime = exist.GetBaseEntity().UpdateTime
		return nil, commEntityManager.UpdateEntity(entity)
	}
}

func (e *operateMonitorTaskManageController) deleteEntity(context httpserver.Context) (interface{}, error) {
	str := context.Query("id")
	if str == "" {
		return nil, errors.New("输入的id为null")
	}

	id, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		return nil, err
	}

	exist := commEntityManager.GetEntityById(edgeEntity.Type.OperateMonitorTaskEntity.Type(), id)
	if exist == nil {
		return nil, errors.New("实体不存在")
	}

	err = commEntityManager.DeleteEntity(exist)
	if err != nil {
		return nil, err
	}

	return commEntity.BuildMap(exist), nil
}

func (e *operateMonitorTaskManageController) deleteEntityList(context httpserver.Context) (interface{}, error) {
	ids := context.Query("ids")

	idList := strings.Split(ids, ",")
	for _, str := range idList {
		if str == "" {
			continue
		}
		id, err := strconv.ParseInt(str, 10, 64)
		if err != nil {
			return nil, err
		}

		exist := commEntityManager.GetEntityById(edgeEntity.Type.OperateMonitorTaskEntity.Type(), id)
		if exist == nil {
			return nil, errors.New("实体不存在")
		}

		err = commEntityManager.DeleteEntity(exist)
		if err != nil {
			return nil, err
		}
	}

	return nil, nil
}
